//
//  PPPetPhotoViewController.m
//  pet
//
//  Created by 陈无忌 on 12/11/14.
//  Copyright (c) 2014 whalefin. All rights reserved.
//

#import "PPEditPetPhotoViewController.h"
#import "supportingHeadFiles.h"
#import "PPWaterFallsView.h"
#import "ELCImagePickerController.h"
#import "ELCImagePickerHeader.h"
#import "PPCameraAuthorization.h"
#import "PPSystemConfiguraton.h"
#import "petPhotoModel.h"

@interface PPEditPetPhotoViewController ()<UIImagePickerControllerDelegate,UINavigationControllerDelegate,ELCImagePickerControllerDelegate,UIActionSheetDelegate>
@property (weak, nonatomic) IBOutlet PPWaterFallsView *waterView;
@property (strong, nonatomic) NSMutableArray *imageArray;
@property (strong, nonatomic) NSMutableArray *disPlayArray;

@property (strong, nonatomic) NSMutableArray *insertImgArray;
@property (strong, nonatomic) NSMutableArray *deleteImgArray;
@property (weak, nonatomic) IBOutlet UIView *editToolView;

@property (strong, nonatomic) NSMutableArray *selectImgArray;

@property (strong, nonatomic) UIImagePickerController *imagePicker;
@property (weak, nonatomic) PPSystemConfiguraton *config;

@property (nonatomic) int operateCount;

@property (nonatomic, strong) NSMutableArray *uploadArray;

@end

@implementation PPEditPetPhotoViewController

- (PPSystemConfiguraton *)config
{
    if (!_config) {
        _config = [PPSystemConfiguraton sharedSystemConfiguration];
    }
    return _config;
}

- (UIImagePickerController *)imagePicker
{
    if (!_imagePicker) {
        _imagePicker = [[UIImagePickerController alloc] init];
        _imagePicker.allowsEditing = NO;
        _imagePicker.delegate = self;
    }
    return _imagePicker;
}

- (NSMutableArray *)insertImgArray
{
    if (!_insertImgArray) {
        _insertImgArray = [NSMutableArray array];
    }
    return _insertImgArray;
}

- (NSMutableArray *)deleteImgArray
{
    if (!_deleteImgArray) {
        _deleteImgArray = [NSMutableArray array];
    }
    return _deleteImgArray;
}

- (NSMutableArray *)selectImgArray
{
    if (!_selectImgArray) {
        _selectImgArray = [NSMutableArray array];
    }
    return _selectImgArray;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    [HUD showUIBlockingIndicatorWithText:@"正在加载"];
    self.editToolView.hidden = NO;
    self.waterView.isEdit = YES;
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(showWhichPhotoSelect:) name:@"reciveClickPhoto" object:nil];
    

    
    dispatch_async(dispatch_get_main_queue(), ^{
        self.imageArray = [[NSMutableArray alloc] init];
        for (PPPetPhoto *photo in self.pet.petImgList) {
            NSData *data = [NSData dataWithContentsOfURL:[PPImageUrl getImageUrlOriginal:photo.img]];
            UIImage *image = [UIImage imageWithData:data];
            petPhotoModel *photoModel = [[petPhotoModel alloc] initWithImage:image AndImageId:photo.id];
            [self.imageArray addObject:photoModel];
        }
        self.disPlayArray = [self.imageArray mutableCopy];
        [self.waterView setWithDataArray:self.disPlayArray];
        [HUD hideUIBlockingIndicator];

    });
    
    }


- (void)dealloc
{
    [[NSNotificationCenter defaultCenter] removeObserver:self];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

- (void)showWhichPhotoSelect:(NSNotification *)notification
{
    NSDictionary *data = notification.userInfo;
    petPhotoModel *img = data[@"img"];
    if ([self.selectImgArray containsObject:img]) {
        [self.selectImgArray removeObject:img];
    }else{
        [self.selectImgArray addObject:img];
    }
    NSLog(@"select img array is %@",self.selectImgArray);
}

- (IBAction)addPetPhotoButton:(id)sender {
    if (self.selectImgArray.count > 0) {
        [self alertShow:@"添加图片请先清除选择"];
        return;
    }
    [self addPhoto];
}

- (IBAction)deletePetPhotoButton:(id)sender {
    if (self.selectImgArray.count > 0) {
        for (petPhotoModel *selectImg in self.selectImgArray) {
            if ([self.imageArray containsObject:selectImg]) {
                //如果图片存在源数据源 则加入删除数组
                [self.deleteImgArray addObject:selectImg];
            }else if ([self.insertImgArray containsObject:selectImg]){
                //否则 从新增图片数组进行匹配 有之则删除
                [self.insertImgArray removeObject:selectImg];
            }
            //从展示数组中移除
            [self.disPlayArray removeObject:selectImg];
        }
        NSLog(@"delete img array is %@",self.deleteImgArray);
        NSLog(@"display img array is %@",self.disPlayArray);
        //重新加载展示队列
        //删除后重新选择
        [self.selectImgArray removeAllObjects];
        [self.waterView setWithDataArray:self.disPlayArray];
        
    }else{
        [self alertShow:@"请先选择一张图片"];
    }
}

- (IBAction)saveEditButton:(id)sender {
    if (self.selectImgArray.count > 0) {
        [self alertShow:@"保存修改请先清除选择"];
        return;
    }
    if (self.disPlayArray.count >= 3) {
        int count;
        if (self.insertImgArray.count == 0 && self.deleteImgArray.count == 0) {
            //结束编辑
            self.waterView.isEdit = NO;
            self.disPlayArray = [self.imageArray mutableCopy];
            [self.waterView setWithDataArray:self.disPlayArray];
            CGRect frame = self.waterView.frame;
            frame.size.height += 40;
            self.waterView.frame = frame;
            self.editToolView.hidden = YES;
            [self.navigationItem.rightBarButtonItem setTitle:@"编辑"];
            return;
        }else if (self.insertImgArray.count == 0 && self.deleteImgArray.count != 0) {
            count = 1;
        }else if (self.insertImgArray.count != 0 && self.deleteImgArray.count == 0){
            count = 1;
        }else{
            count = 2;
        }
        [HUD showUIBlockingIndicator];
        if (self.deleteImgArray.count > 0) {
            //删除图片
            NSString *deleteUrl = [PPAPIList getAPIList].PPDeletePetImg;
            NSString *idString = @"";
            for (petPhotoModel *model in self.deleteImgArray) {
                NSString *str = [NSString stringWithFormat:@"%d",model.imgId];
                idString = [idString stringByAppendingString:str];
                idString = [idString stringByAppendingString:@","];
            }
            idString = [idString substringWithRange:NSMakeRange(0, idString.length - 1)];
            NSDictionary *params = @{@"imgIdString":idString};
            [httpRequst POST:deleteUrl parameters:params success:^(AFHTTPRequestOperation *operation, id responseObject) {
                [self.deleteImgArray removeAllObjects];
                self.operateCount ++;
                if (self.operateCount == count) {
                    [self reloadAllData];
                }
            } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
                [HUD hideUIBlockingIndicator];
                [self alertShow:@"图片删除失败"];
            }];
        }
        if (self.insertImgArray.count > 0) {
            //上传图片
            self.uploadArray = [NSMutableArray array];
            //先处理图片
            int i = 0;
            for (petPhotoModel *model in self.insertImgArray) {
                UIImage *pubImage = model.image;
                NSData *data;
                if (UIImagePNGRepresentation(pubImage).length > 1000000 && UIImagePNGRepresentation(pubImage).length <= 10000000) {
                    data = UIImageJPEGRepresentation(pubImage, 0.5);
                }else if (UIImagePNGRepresentation(pubImage).length <= 1000000){
                    data = UIImagePNGRepresentation(pubImage);
                }else if (UIImagePNGRepresentation(pubImage).length > 10000000 && UIImagePNGRepresentation(pubImage).length <= 20000000){
                    data = UIImageJPEGRepresentation(pubImage, 0.3);
                }else{
                    data = UIImageJPEGRepresentation(pubImage, 0.1);
                }
                //图片保存的路径
                //这里将图片放在沙盒的documents文件夹中
                NSString * DocumentsPath = [NSHomeDirectory() stringByAppendingPathComponent:@"Documents"];
                //文件管理器
                NSFileManager *fileManager = [NSFileManager defaultManager];
                //把刚刚图片转换的data对象拷贝至沙盒中 并保存为image.png
                [fileManager createDirectoryAtPath:DocumentsPath withIntermediateDirectories:YES attributes:nil error:nil];
                [fileManager createFileAtPath:[DocumentsPath stringByAppendingString:[NSString stringWithFormat:@"/image%d",i]] contents:data attributes:nil];
                //得到选择后沙盒中图片的完整路径
                NSString *filePath = [[NSString alloc]initWithFormat:@"%@%@",DocumentsPath,  [NSString stringWithFormat:@"/image%d",i]];
                NSLog(@"%@",filePath);
                [self.uploadArray addObject:filePath];
                i++;
            }
            //开始网络请求
            NSString *insertUrl = [PPAPIList getAPIList].PPAddPetImg;
            NSDictionary *params = @{@"petId":@(self.pet.id)};
            [httpRequst POST:insertUrl parameters:params imagePathArray:self.uploadArray imageName:@"image" keyWords:@"img" success:^(AFHTTPRequestOperation *operation, id responseObject) {
                [self.insertImgArray removeAllObjects];
                self.operateCount ++;
                if (self.operateCount == count) {
                    [self reloadAllData];
                }
            } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
                [HUD hideUIBlockingIndicator];
                [self alertShow:@"上传图片太多，请分配上传"];
                NSLog(@"error %@",error);
            }];

        }
    }else{
        [self alertShow:@"至少需要3张宠物照片"];
    }
}


- (void) reloadAllData
{
    //更新本地宠物信息
    [self.config getPetListwithComepletion:nil];
    //更新当前宠物信息
    [HUD hideUIBlockingIndicator];
    NSString *url = [PPAPIList getAPIList].PPQueryPetById;
    NSDictionary *params = @{@"petId":@(self.pet.id)};
    [httpRequst POST:url parameters:params success:^(AFHTTPRequestOperation *operation, id responseObject) {
        NSNumber *processResult = responseObject[@"processResult"];
        if (processResult.boolValue) {
            NSDictionary *resultMap = responseObject[@"resultMap"];
            NSDictionary *petDic = resultMap[@"pet"];
            NSError *err = nil;
            PPPetInfo *pet = [[PPPetInfo alloc] initWithDictionary:petDic error:&err];
            [self.imageArray removeAllObjects];
            for (PPPetPhoto *photo in pet.petImgList) {
                //        NSString *imgName = imgDic[@"img"];
                NSData *data = [NSData dataWithContentsOfURL:[PPImageUrl getImageUrlOriginal:photo.img]];
                UIImage *image = [UIImage imageWithData:data];
                petPhotoModel *photoModel = [[petPhotoModel alloc] initWithImage:image AndImageId:photo.id];
                [self.imageArray addObject:photoModel];
            }
            self.waterView.isEdit = NO;
            self.disPlayArray = [self.imageArray mutableCopy];
            [self.waterView setWithDataArray:self.disPlayArray];
            self.pet.petImgList = pet.petImgList;
        }
    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
        
    }];
}

- (void)alertShow:(NSString *)msg
{
    UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"提示" message:msg delegate:nil cancelButtonTitle:@"确定" otherButtonTitles: nil];
    [alert show];
}

- (void)addPhoto {
    UIActionSheet *choiceSheet = [[UIActionSheet alloc] initWithTitle:nil
                                                             delegate:self
                                                    cancelButtonTitle:@"取消"
                                               destructiveButtonTitle:nil
                                                    otherButtonTitles:@"拍照", @"从相册中选取", nil];
    [choiceSheet showInView:self.view];
}

#pragma mark - Action Sheet Delegate
-(void)actionSheet:(UIActionSheet *)actionSheet clickedButtonAtIndex:(NSInteger)buttonIndex{
    if (buttonIndex == 2) {
        return;
    }else if (buttonIndex == 1) {
        //从相册中选择 使用ELCImagePicker
        ELCImagePickerController *elcImagePicker = [[ELCImagePickerController alloc] initImagePicker];
        elcImagePicker.imagePickerDelegate = self;
        elcImagePicker.maximumImagesCount = 9;
        elcImagePicker.onOrder = YES;
        [self.navigationController presentViewController:elcImagePicker animated:YES completion:nil];
    }else if (buttonIndex == 0){
        //拍照
        if ([UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypeCamera]) {
            //拍照功能可用
            if (IS_OS_7_OR_LATER) {
                //iOS7以后版本 检测授权
                [PPCameraAuthorization getCameraAuthorization];
                if (!self.config.isCameraValid) {
                    //未授权 提示设置
                    UIAlertView *alert = [[UIAlertView alloc] initWithTitle:nil message:@"请在iPhone的“设置-隐私-相机”选项中，允许程序访问你的相机" delegate:nil cancelButtonTitle:@"知道了" otherButtonTitles:nil];
                    [alert show];
                    return;
                }else{
                    //授权 正常使用
                    [self.imagePicker setSourceType:UIImagePickerControllerSourceTypeCamera];
                }
            }else{
                //iOS6正常使用
                [self.imagePicker setSourceType:UIImagePickerControllerSourceTypeCamera];
            }
            [self presentViewController:self.imagePicker animated:YES completion:nil];
        }else{
            //功能不可用 去相册
            ELCImagePickerController *elcImagePicker = [[ELCImagePickerController alloc] initImagePicker];
            elcImagePicker.imagePickerDelegate = self;
            elcImagePicker.maximumImagesCount = 9;
            elcImagePicker.onOrder = YES;
            [self.navigationController presentViewController:elcImagePicker animated:YES completion:nil];
        }
    }
}

#pragma mark - ELCImagePickerControllerDelegate
- (void)elcImagePickerController:(ELCImagePickerController *)picker didFinishPickingMediaWithInfo:(NSArray *)info
{
    for (NSDictionary *dict in info) {
        if ([dict objectForKey:UIImagePickerControllerMediaType] == ALAssetTypePhoto){
            if ([dict objectForKey:UIImagePickerControllerOriginalImage]){
                EYLargePhoto *photo = [[EYLargePhoto alloc] init];
                photo.thumb = [dict objectForKey:UIImagePickerControllerOriginalImage];
                UIImage* image = photo.thumb;
                petPhotoModel *model = [[petPhotoModel alloc] initWithImage:image AndImageId:0];
                
                //获得照片加入insertImgArray
                [self.insertImgArray addObject:model];
                //获得照片加入displayArray
                [self.disPlayArray addObject:model];
            } else if ([dict objectForKey:UIImagePickerControllerEditedImage]){
                NSLog(@"UIImagePickerControllerReferenceURL = %@", dict);
            }
        }
    }
    NSLog(@"insert img array is %@",self.insertImgArray);
    NSLog(@"display img array is %@",self.disPlayArray);
    [picker dismissViewControllerAnimated:YES completion:^{
        //返回刷新waterFallView
        [self.waterView setWithDataArray:self.disPlayArray];
    }];
}


- (void)elcImagePickerControllerDidCancel:(ELCImagePickerController *)picker
{
    [picker dismissViewControllerAnimated:YES completion:nil];
}


#pragma mark - UIImagePickControllerDelegate
- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info
{
    UIImage *image = [info valueForKey:UIImagePickerControllerOriginalImage];
    petPhotoModel *model = [[petPhotoModel alloc] initWithImage:image AndImageId:0];
    //获得照片加入insertImgArray
    [self.insertImgArray addObject:model];
    //获得照片加入displayArray
    [self.disPlayArray addObject:model];
    NSLog(@"insert img array is %@",self.insertImgArray);
    NSLog(@"display img array is %@",self.disPlayArray);
    [self.imagePicker dismissViewControllerAnimated:YES completion:^{
        [self.waterView setWithDataArray:self.disPlayArray];
    }];
}


/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
